/*
 This file is part of WebHUD.
 
 WebHUD is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 any later version.
 
 WebHUD is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with WebHUD.  If not, see <http://www.gnu.org/licenses/>.
 */

#import "WHController.h"
#import "Constants.h"
#import "Safari.h"
#import "WHApi.h"
#import "WHHelper.h"
#import "LocationChangeHandler+WHWebFrameLoadDelegate.h"

@implementation WHController

@synthesize panel;
@synthesize webview;
@synthesize tabview;
@synthesize urls;
@synthesize order;

+ (void)initialize
{
	// Force the creation of the singleton
	[WHController sharedController];
}

static WHController *sharedController = nil;

+ (WHController*)sharedController
{
    @synchronized(self) {
        if (sharedController == nil) {
            [[self alloc] init];
        }
    }
    return sharedController;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sharedController == nil) {
            sharedController = [super allocWithZone:zone];
            return sharedController;
        }
    }
    return nil;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (unsigned)retainCount
{
    return UINT_MAX;
}

- (void)release
{
    // do nothing
}

- (id)autorelease
{
    return self;
}

- (BOOL)loadMyNibFile
{
    // The myNib file must be in the bundle that defines self's class.
    if (![NSBundle loadNibNamed:@"WebHUD" owner:self])
    {
        NSLog(@"Warning! Could not load 'WebHUB' nib file.\n");
        return NO;
    }
    return YES;
}


- (id)init
{	
	self = [super init];
	if (self != nil) {
		
		if (!([[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"com.apple.Safari"] ||
			  [[[NSBundle mainBundle] bundleIdentifier] isEqualToString:@"org.webkit.nightly.WebKit"]
			  ))
			return nil;
		
		NSFileManager *fm = [NSFileManager defaultManager];
		NSString *applicationSupportFolderPath = [WHPaths applicationSupportFolderPath];
		
		NSMutableDictionary *defaults = [NSMutableDictionary dictionaryWithContentsOfFile:
										 [[NSBundle bundleWithIdentifier:BundleIdentifier] pathForResource:@"Defaults" ofType:@"plist"]];
		
		[[NSUserDefaults standardUserDefaults] registerDefaults:defaults];
		
		if (![fm fileExistsAtPath:applicationSupportFolderPath]) {
			if (![fm createDirectoryAtPath:applicationSupportFolderPath withIntermediateDirectories:YES attributes:nil error:nil])
				return nil;
		}
		
		
		// The magic happens here!
		[LocationChangeHandler swizzle];
		
		// load Nib File
		if (![self loadMyNibFile]) {
			return nil;
		}
		
		NSLog(@"WHController::init() panel= %@", self.panel);
	}
	return self;
}

- (void)showHUDForWebView:(WebView *)masterWebview
			     andFrame:(WebFrame *)frame
{
	//WebScriptObject *wso = [masterWebview windowScriptObject];	
	//WHApi *api = [[WHApi alloc] init];
    
    //api.foo = @"Foo Bar!";
    
	//[wso setValue:api forKey:@"WebHUD"];
	
	// remove all tabs
	for (NSTabViewItem *tvItem in [tabview tabViewItems]) {
		[tabview removeTabViewItem: tvItem];
	}
	
	// create the tabs for each title in dict
	for (NSString *title in order) {
		NSTabViewItem *tvItem = [[NSTabViewItem alloc] init];
        
        [tvItem setLabel: title];
		[tvItem setView: webview];
        
		[tabview addTabViewItem:tvItem];
	}
	
	[tabview selectTabViewItemAtIndex: 0];
	[panel setIsVisible: YES];
}

/**********************************************************************
 * NSTabView Delegate Methods
 */
- (void)tabView:(NSTabView *)tabView didSelectTabViewItem:(NSTabViewItem *)tabViewItem
{
	NSLog(@"Selected tab %@", tabViewItem);
	
	NSString *url = [urls objectForKey: [tabViewItem label]];
	NSLog(@"URL to load: %@", url);
	
	[[webview mainFrame] loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString: url]]];

}

/**********************************************************************
 * Version etc (WTF??)
 */
+ (NSString *)version
{
	return [[NSBundle bundleWithIdentifier:BundleIdentifier] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
}

+ (NSString *)userAgent
{
	return [NSString stringWithFormat:UserAgentFormat, [WHController version]];
}

@end
